package com.xhu.water_supply.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @Description 全局跨域过滤器

 */
@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
//        config.addAllowedOrigin("*");
        config.addAllowedOriginPattern("*");    //SpringBoot2.4后
        config.addAllowedHeader("*");

        // 允许cookies跨域
        config.setAllowCredentials(true);

        // 预检请求的缓存时间（秒），即在这个时间段里，对于相同的跨域请求不会再预检了
        config.setMaxAge(18000L);

        // 允许提交请求的方法类型，*表示全部允许
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");

        config.addExposedHeader("set-cookie");
        config.addExposedHeader("access-control-allow-headers");
        config.addExposedHeader("access-control-allow-methods");
        config.addExposedHeader("access-control-allow-origin");
        config.addExposedHeader("access-control-max-age");
        config.addExposedHeader("X-Frame-Options");

        // 添加映射路径，拦截所有请求
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        // 返回一个配置好的跨域过滤器
        return new CorsFilter(configSource);
    }
}